<template>
  <div class="targetTable">
    <el-table
      ref="table"
      v-loading="loading"
      :row-key="rowkey"
      :reserve-selection="true"
      :show-header="showHeader"
      :data="realTableData"
      :row-class-name="tableRowClassName"
      :height="tableHeight"
      :row-style="{ height: rowheight || '' }"
      element-loading-text="加载中"
      :style="{ width: '100%', minHeight: minHeight }"
      :empty-text="noDataShow"
      :show-overflow-tooltip="showOverflowTooltip"
      v-bind="$attrs"
      @row-click="singleElection"
      @selection-change="handleSelectionChange"
    >
      <!-- 空数据展示，可以不用 -->
      <template slot="empty">
        <!-- <img src="@/assets/kongshuju.png" alt="" style="width:50px;height:50px;" class="mt-20"> -->
        <p class="noCart">{{ noDataShow }}</p>
      </template>
      <!-- 是否有全选列 -->
      <el-table-column
        v-if="selection"
        :fixed="commonFixed ? '' : false"
        :selectable="selectFn"
        align="center"
        width="45"
        type="selection"
      />
      <!-- 是否有单选框 -->
      <el-table-column v-if="radiobox" align="center" width="35">
        <template slot-scope="scope">
          <!-- 可以手动的修改label的值，从而控制选择哪一项 -->
          <el-radio v-model="templateSelection" class="radio" :label="scope.row.id">&nbsp;</el-radio>
        </template>
      </el-table-column>
      <!-- 是否有展开列 -->
      <el-table-column v-if="expand" type="expand">
        <template v-if="props.row.children" slot-scope="props">
          <hk-table
            style="padding-left: 30px"
            :table-data="props.row.children"
            :table-columns="tableColumns"
            :expand="!!props.row.children"
            :operate="true"
            :show-pag="false"
          />
        </template>
      </el-table-column>
      <!-- 是否显示序号 -->
      <el-table-column
        v-if="showIndex"
        label="序号"
        align="center"
        :fixed="commonFixed ? '' : false"
        width="80"
        type="index"
        :index="indexMethod"
      />
      <!-- prop是对应列内容的字段名 width是对应列宽度 sortable是是否排序 label是对应列名称 -->

      <el-table-column
        v-for="(item, index) in tableColumns"
        :key="index"
        :sortable="item.sortable"
        :prop="item.param"
        :width="item.width ? item.width : ''"
        :label="item.label"
        :show-overflow-tooltip="item.showToolTip?false: true"
        :align="item.align || 'left'"
        :fixed="item.fixed"
      >
        <!-- 具名插槽 -->
        <template slot-scope="scope">
          <template v-if="item.type == 'slot'">
            <slot :name="item.param" :row="isNeedIndex ? scope : scope.row" />
          </template>
          <el-form v-else-if="item.type" :model="scope.row" size="small">
            <el-form-item :rules="item.rules &&rules[item.rules] " :prop="item.param">

              <template v-if="item.type == 'input'">
                <el-input
                  v-model="scope.row[item.param]"
                  :clearable="true"
                  style="width: 100%"
                  :maxlength="item.maxlength"
                />
              </template>
              <template v-else-if="item.type == 'textarea'">
                <el-input
                  v-model="scope.row[item.param]"
                  type="textarea"
                  :clearable="true"
                  style="width: 100%"
                  :maxlength="item.maxlength"
                />
              </template>
              <template v-else-if="item.type == 'select'">
                <el-select
                  v-model="scope.row[item.param]"
                  :clearable="true"
                  placeholder="请选择"
                  :disabled="item.disabled"
                  v-bind="item.attrs"
                  style="width: 100%"
                >
                  <el-option v-for="(el, index) in dictList[item.list]" :key="index" :label="el.label" :value="el.value" />
                </el-select>
              </template>
              <!--    日期选择器    -->
              <el-date-picker
                v-else-if="item.type == 'datePicker'"
                v-model="scope.row[item.param]"
                style="width: 100%"
                type="date"
                placeholder="选择日期"
                :value-format="item.format"
              />
            </el-form-item>
          </el-form>
          <template v-else>
            <span v-if="!item.hidden">{{ scope.row[item.param] }}</span>
          </template>

        </template>
      </el-table-column>
      <!-- 操作插槽 -->
      <el-table-column v-if="operate" label="操作" align="center" :fixed="commonFixed ? 'right' : false" :width="operateWidth">
        <template slot-scope="scope">
          <slot :row="isNeedIndex ? { row: scope.row, index: scope.$index } : scope.row" name="operate" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <pagination
      v-if="total >= 0 && showPag"
      class="el-input__page"
      :total="total"
      :page.sync="queryParamsData.current"
      :limit.sync="queryParamsData.size"
      @pagination="changePage"
    />
  </div>
</template>

<script>
export default {
  name: 'HkTable',
  props: {
    rules: {
      type: Object,
      default: () => {}
    },
    dictList: {
      type: Object,
      default: () => {}
    },
    isNeedIndex: {
      type: Boolean,
      default() {
        return false
      }
    },
    // 是否显示单选框
    radiobox: {
      type: Boolean,
      default: false
    },
    total: {
      // eslint-disable-next-line vue/require-prop-type-constructor
      type: Number | String,
      default: 0
    },
    rowkey: {
      // eslint-disable-next-line vue/require-prop-type-constructor
      type: String | Function,
      default: ''
    },
    selectThing: {
      type: Boolean,
      default: false
    },
    showOverflowTooltip: {
      type: Boolean,
      default: true
    },
    showHeader: {
      // 是否显示表头
      type: Boolean,
      default: true
    },
    loading: {
      // 预加载
      type: Boolean,
      default: false
    },
    selectFn: {
      // 全选禁用方法
      type: Function,
      default: () => {
        return true
      }
    },
    tableData: {
      // 表格数据
      type: Array,
      default: () => {
        return []
      }
    },
    tableColumns: {
      // 表头数据
      type: Array,
      default: () => {
        return []
      }
    },

    expand: {
      // 展开
      type: Boolean,
      default: false
    },
    selection: {
      // 全选
      type: Boolean,
      default: false
    },
    selectionFixed: {
      // 全选是否固定
      type: Boolean,
      default: false
    },
    // 前面和操作面是否固定
    commonFixed: {
      // 全选是否固定
      type: Boolean,
      default: false
    },
    showIndex: {
      // 顺序
      type: Boolean,
      default: false
    },
    operate: {
      // 操作
      type: Boolean,
      default: false
    },
    // 操作栏位的宽度
    operateWidth: {
      // 操作
      type: String | Number,
      default: ''
    },
    tableHeight: {
      // 高度
      type: [Number, String],
      default: () => null
    },
    rowheight: {
      // 行高
      type: String,
      default: () => null
    },
    minHeight: {
      type: String,
      default: () => '0px'
    },
    noDataShow: {
      // table中间无数据展示
      type: String,
      default: () => '暂无数据'
    },
    // 分页器部分
    queryParams: {
      type: Object,
      default: () => {
        return { current: 1, size: 10 }
      }
    },
    // 是否显示分页器
    showPag: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      isloading: this.loading,
      realTableData: [],
      templateSelection: '',
      checkList: []
    }
  },
  computed: {
    queryParamsData() {
      return this.queryParams
    }
  },
  watch: {

    tableData: {
      handler(newsVal) {
        this.getList()
      },
      deep: true
    },
    realTableData: {
      handler(newsVal) {
        this.showSelected()
      },
      deep: true
    },
    total: {
      handler(newsVal, oldValue) {
        if (this.queryParamsData.current > 1 && newsVal % this.queryParamsData.size == 0 && newsVal < oldValue) {
          this.queryParamsData.current--
          this.changePage()
        }
      }
    },
    // templateSelection: {
    //   handler(newsVal) {
    //  console.log('tem',newsVal);
    //   },
    //  immediate:true
    // }
    queryParams: {
      handler(newsVal, oldValue) {
        if (!(newsVal?.scrollToTop || this.loading)) return
        this.$nextTick(() => {
          this.$refs.table.bodyWrapper.scrollTop = 0
        })
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    this.getList()

    this.showSelected()
  },
  methods: {
    indexMethod(index) {
      if (!this.queryParamsData.current || !this.queryParamsData.size) {
        return index + 1
      } else {
        this.queryParamsData.current = this.queryParamsData.current >= 1 ? this.queryParamsData.current : 1
        return index + (this.queryParamsData.current - 1) * this.queryParamsData.size + 1
      }
    },
    // 单选
    singleElection(row) {
      this.templateSelection = row.id
      this.checkList = this.tableData.filter((item) => item.id === row.id)
      this.$emit('singleElection', this.checkList)
    },

    // 获取列表
    getList() {
      this.realTableData = this.tableData
    },
    changePage() {
      /* const tableBodys = $('.el-table__fixed-body-wrapper .el-table__body')
      console.log(tableBodys.length)
      for (let i = 0; i < tableBodys.length; i++) {
        tableBodys[i].scrollTop = 0
      } */
      this.$refs.table.bodyWrapper.scrollTop = 0
      this.$emit('changePage', {
        current: this.queryParamsData.current,
        size: this.queryParamsData.size
      })
    },
    selectableFn(row, index) {},

    // 多选
    handleSelectionChange(val) {
      this.$emit('handleSelectionChange', val)
    },
    tableRowClassName(row, rowIndex) {
      // 有空优化
      if (this.$parent.tableRowColor) {
        return this.$parent.tableRowColor(row, rowIndex)
      }
    },
    // 按钮点击事件
    // methods方法名 row当前点击列数据 index当前点击的index
    handleButton(methods, row, index) {
      this.$emit('clickButton', { methods: methods, row: row, index: index })
    },
    deleteSalaryFn(n) {
      console.log(n)
    },
    // 筛选数据显示为选中
    showSelected() {
      if (this.selectThing) {
        this.$nextTick(() => {
          this.realTableData.forEach((item) => {
            if (item.flag) {
              this.$refs.table.toggleRowSelection(item)
            }
          })
        })
      }
    },

    toggleRow(item) {
      this.$refs.table.toggleRowSelection(item)
    },
    // 清空选中项
    clearSelection() {
      this.$refs['table'].clearSelection()
    }
  }
}
</script>

<style lang="scss" scoped>
.targetTable {
  flex: 1;
  position: relative;
  // padding-bottom: 20px;
  display: flex;
  flex-direction: column;
  .el-table {
    flex: 1;
    overflow: auto;
  }
}
.pagination-container{
  text-align: right;
}
.el-form .el-form-item{
  margin: 5px 0 13px ;
}

::v-deep{
  .el-form-item__error{
   font-size: 10px;
  }
  .el-table__cell{
    padding: 7px 0 !important;
  }
}
</style>
